package com.leessy.r229.kt

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.schedulers.Schedulers


/************************************** Rx ************************************************/
fun <T> Observable<T>.observeOnMain(): Observable<T> {
    return this.observeOn(AndroidSchedulers.mainThread())
}

fun <T> Observable<T>.observeOnComputation(): Observable<T> {
    return this.observeOn(Schedulers.computation())
}

fun <T> Observable<T>.observeOnIo(): Observable<T> {
    return this.observeOn(Schedulers.io())
}

fun <T> Observable<T>.observeOnNew(): Observable<T> {
    return this.observeOn(Schedulers.newThread())
}

fun <T> Observable<T>.subscribeOnMain(): Observable<T> {
    return this.subscribeOn(AndroidSchedulers.mainThread())
}

fun <T> Observable<T>.subscribeOnComputation(): Observable<T> {
    return this.subscribeOn(Schedulers.computation())
}

fun <T> Observable<T>.subscribeOnIo(): Observable<T> {
    return this.subscribeOn(Schedulers.io())
}

fun <T> Observable<T>.subscribeOnNew(): Observable<T> {
    return this.subscribeOn(Schedulers.newThread())
}


/**Observable 绑定 Compose */
fun <T> Observable<T>.bindToLifecycle(action: (Observable<T>) -> Observable<T>): Observable<T> {
    return action(this)
}

///**使用RxJava实现*** 在io线程执行一些逻辑，并在main线程处理结果,如果使用的 Lifecycle类型自动绑定 bindToLifecycle*/
//fun <T, R> T.RxIo_Main(
//    actionIO: (T) -> R,
//    actionMain: (R) -> Unit
//) {
//    val o = Observable.just(0)
//        .observeOnIo().map { actionIO(this@RxIo_Main) }
//    when (this) {
//        is RxAppCompatActivity -> o.compose(this.bindToLifecycle()).observeOnMain()
//        is RxAppCompatDialogFragment -> o.compose(this.bindToLifecycle()).observeOnMain()
//        is RxFragment -> o.compose(this.bindToLifecycle()).observeOnMain()
//        is RxFragmentActivity -> o.compose(this.bindToLifecycle()).observeOnMain()
//        is RxDialogFragment -> o.compose(this.bindToLifecycle()).observeOnMain()
//        else -> o.observeOnMain()
//    }.subscribe({
//        actionMain(it)
//    }, {})
//}
//
///**使用RxJava实现*** 在io线程执行一些逻辑，并在main线程处理结果*/
//fun <T, R> T.RxIo_Main(
//    compose: (Observable<T>) -> Observable<T> = { it },
//    actionIO: (T) -> R,
//    actionMain: (R) -> Unit
//) {
//    compose(Observable.just(this))
//        .observeOnIo()
//        .map {
//            actionIO(this@RxIo_Main)
//        }
//        .observeOnMain()
//        .subscribe {
//            actionMain(it)
//        }
//}
/************************************** Rx ************************************************/




